package com.example.demo.web.controller;

import com.example.demo.web.entity.MyData;
import com.example.demo.web.repository.MyDataRepository;
import lombok.Data;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.transaction.Transactional;
import java.util.Optional;

@RestController
@RequestMapping("/my-data")
public class MyDataController {
    private final MyDataRepository myDataRepository;

    public MyDataController(MyDataRepository myDataRepository) {
        this.myDataRepository = myDataRepository;
    }


    @Data
    public static class CreateMyDataRequest {
        private String name;
    }

    @PostMapping()
    public MyData insert(@RequestBody CreateMyDataRequest request) {
        return myDataRepository.save(MyData.builder()
                .name(request.getName())
                .build());
    }

    @PutMapping("{id}")
    @Transactional
    public MyData update(@PathVariable(name = "id") long id, @RequestBody CreateMyDataRequest request) {
        Optional<MyData> result = myDataRepository.findById(id);
        MyData mydata = result.get();
        mydata.setName(request.getName());
        myDataRepository.save(mydata);
        return mydata;
    }
}
